import api from '../utils/api'
const userInfoList = [
    { key: 'nickname', page: '/pages/login/nickname' },
    { key: 'wechatimg', page: '/pages/login/headimg' },
    { key: 'birthday', page: '/pages/login/birthday'  },
    { key: 'gender', page: '/pages/login/sex' },
    { key: 'height', page: '/pages/login/height' },
    { key: 'weight', page: '/pages/login/weight' }
]
export const getNext = (key, info) => {
    const userInfo = info || wx.getStorageSync('userInfo')
    if(!userInfo) {
        return userInfoList[0]
    } else {
        const list = key
            ? userInfoList.slice(userInfoList.findIndex(p => p.key == key)+1)
            : userInfoList
        for(const p in list) {
            const prop = list[p]
            if(!userInfo[prop.key]) {
                return prop
            }
        }
        return null
    }
}
    
export const stepNext = (key, userInfo) => {
    const step = getNext(key, userInfo)
    if(step) {
        wx.navigateTo({
            url: step.page
        })
    } else if(!step && key) {
        wx.navigateTo({
            url: "/pages/login/loginfinesh"
        })
    } else {
        console.log('222');
        wx.reLaunch({
            url: "/pages/home/index"
        })
    }
}
export const stepSkip = () => {
    wx.reLaunch ({
        url: "/pages/home/index"
    })
}

export const saveUserInfo = (data = {}) => {
    return new Promise((resolve, reject) => {
        api.post('/api/hxhealth/user/save', {
            data: data,
        }).then(res => {
            resolve(res)
        }).catch(e => {
            reject(e)
        })
    })
}

export const saveUserAndStorage = async (userInfo = {}) => {
    return new Promise(async (resolve)=> {
        try{
            const res = await saveUserInfo(userInfo)
            wx.setStorageSync('userInfo', res?.[0])
            wx.showToast({
                title: '保存成功',
                icon: 'none',
                duration: 1000,
                complete:(res) => {
                    resolve(true)
                }
            })
        }catch(e) {
            resolve(false)
        }
    })
}